//
//  TMGGoldPartnerViewController.m
//  TMGold
//
//  Created by Mac on 2017/12/11.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "TMGGoldPartnerViewController.h"
#import "TMGPatnerCollectionViewCell.h"
#import "TMGPatnerDetailViewController.h"
#import "TMGPatnerModel.h"
@interface TMGGoldPartnerViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property(nonatomic, strong) UICollectionView                  *collectionView;
@property(nonatomic, strong) NSMutableArray  <TMGPatnerModel*>                  *dataSouce;
@property(nonatomic, assign) NSInteger                         page;
@property(nonatomic, strong) STLabel                     *titleLable;
@property(nonatomic, strong) NSArray                     *titlesArray;
//弹出框
@property(nonatomic, strong) STButton                     *showButton;
@property(nonatomic, strong) STButton                     *grayButton;
@property(nonatomic, strong) NSMutableArray                     *buttonArrays;
@property(nonatomic, strong) UIView                     *whiteView;

@property(nonatomic, strong) STNoresultView                     *noResultView;
@end

@implementation TMGGoldPartnerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.buttonArrays = [NSMutableArray new];
    self.view.backgroundColor = TM_backgroundColor;
    self.title = @"合作商家";
    [self st_setRightItemWithTitle:@"筛选" titleColor:[UIColor whiteColor]];
    [self configSubView];
    self.page = 1;
    self.dataSouce = [NSMutableArray new];
    [self sendPatnerAddressRequest];
    // Do any additional setup after loading the view.
}
#pragma mark --subView
- (void)configSubView{
    self.titleLable = [[STLabel alloc] initWithFrame:CGRectMake(10, [TMUtils navgationBarBootom], 200, 44)
                                                text:@"所有"
                                           textColor:TM_firstTextColor
                                                font:15
                                         isSizetoFit:NO
                                       textAlignment:NSTextAlignmentLeft];
    [self.view addSubview:self.titleLable];
    __weak typeof(self) weakSelf =  self;
    self.showButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)
                                                title:@"筛选"
                                           titleColor:[UIColor whiteColor]
                                            titleFont:16
                                         cornerRadius:0
                                      backgroundColor:nil
                                      backgroundImage:nil
                                                image:nil];
    self.showButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.showButton setImage:nil forState:UIControlStateSelected];
    self.showButton.right = UIScreenWidth - 15;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.showButton];
    
    [self.showButton setClicAction:^(UIButton *sender) {
        [weakSelf st_rightBarAction:nil];
    }];
    
    UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
    flow.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    flow.minimumLineSpacing = 0;
    flow.minimumInteritemSpacing = 0;
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.titleLable.bottom , UIScreenWidth, [TMUtils tabBarTop] + 49  - self.titleLable.bottom) collectionViewLayout:flow];
    self.collectionView.backgroundColor = TM_backgroundColor;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
#ifdef __IPHONE_11_0
    self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
#else
    self.automaticallyAdjustsScrollViewInsets = NO;
#endif
    [self.collectionView registerClass:[TMGPatnerCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    [self.view addSubview:self.collectionView];
    
    [self configShowView] ;
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self sendPatnerGoodWithAdd:nil];
    }];
    [self.collectionView.mj_header beginRefreshing];
    
    
    //无数据view
    self.noResultView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, 100, UIScreenWidth, 350) title:@"暂无订单" buttonTitle:@"快去购买商品吧" buttonHandle:^(NSString *titleString) {
        
    }];
    self.noResultView.hidden = YES;
    [self.collectionView addSubview:self.noResultView];
    
}
- (void)configShowView{
    __weak typeof(self) weakSelf =  self;
    self.grayButton = [[STButton alloc] initWithFrame:CGRectMake(0, 64, UIScreenWidth, UIScreenHeight - 64)
                                                title:nil
                                           titleColor:nil
                                            titleFont:0
                                         cornerRadius:0
                                      backgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.4]
                                      backgroundImage:nil
                                                image:nil];
    [self.grayButton setClicAction:^(UIButton *sender) {
        [weakSelf st_rightBarAction:nil];
    }];
    self.grayButton.alpha = 0;
    self.grayButton.clipsToBounds = YES;
    [self.view addSubview:self.grayButton];
    
    self.whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    self.whiteView.backgroundColor = [UIColor whiteColor];
    self.whiteView.bottom = 0;
    [self.grayButton addSubview:self.whiteView];
    NSArray * titles = self.titlesArray;
    CGFloat buttonWith = (UIScreenWidth - 80)/3;
    CGFloat buttonHeght = 40;
    for (int i = 0; i < titles.count; i++) {
        STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(10 + 30 * (i%3) + buttonWith * (i%3) , 10+ 10 *(i/3) + i/3 * buttonHeght, buttonWith, buttonHeght)
                                                         title:titles[i]
                                                    titleColor:TM_orangeColor
                                                     titleFont:15
                                                  cornerRadius:8
                                               backgroundColor:[UIColor whiteColor]
                                               backgroundImage:nil
                                                         image:nil];
        buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        
        [buyButton st_setBorderWith:1 borderColor:TM_orangeColor cornerRadius:8];
        __weak typeof(self) weakSelf =  self;
        [buyButton setClicAction:^(UIButton *sender) {
            weakSelf.titleLable.text = sender.currentTitle;
            [weakSelf sendPatnerGoodWithAdd:sender.currentTitle];
            [weakSelf st_rightBarAction:nil];
        }];
        [self.whiteView addSubview:buyButton];
        [self.buttonArrays addObject:buyButton];
        self.whiteView.height = buyButton.bottom  +20;
    }
}
#pragma --mark UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSouce.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellHeight = [TMGPatnerCollectionViewCell cellHeight];
    return CGSizeMake(UIScreenWidth/2 - 20, cellHeight);
}
- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TMGPatnerCollectionViewCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    item.model = self.dataSouce[indexPath.row];
    return item;
}
#pragma --mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TMGPatnerDetailViewController * vc = [TMGPatnerDetailViewController new];
    vc.model = self.dataSouce[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
#pragma mark --Private Method
- (void)reloadData{
    self.noResultView.hidden = self.dataSouce.count;;
    [self.collectionView reloadData];
}
#pragma mark --Action Method
- (void)st_rightBarAction:(id)sender{
    if (!self.titlesArray.count) {
        [self sendPatnerAddressRequest];
        return;
    }
    self.showButton.selected = !self.showButton.selected;
    if (self.showButton.selected) {
        [self alertShow];
    }else{
        [self alrtDismis];
    }
    
}
- (void)alrtDismis{
    [UIView animateWithDuration:0.25 animations:^{
        self.whiteView.bottom = 0;
    } completion:^(BOOL finished) {
        self.grayButton.alpha = 0;
    }];;
}
- (void)alertShow{
    //修改颜色
    for (STButton * button in self.buttonArrays) {
        if ([button.currentTitle isEqualToString:self.titleLable.text]) {
            button.backgroundColor = TM_orangeColor;
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
        }else{
            button.backgroundColor = [UIColor whiteColor];
            [button setTitleColor:TM_orangeColor forState:UIControlStateNormal];
        }
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.whiteView.top = 0;
        
    } completion:^(BOOL finished) {
        self.grayButton.alpha = 1;
    }];
}
#pragma mark --NetWork Method
- (void)sendPatnerAddressRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/personal/getAddress"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 self.titlesArray = responseObject[@"data"];
                                                 [self configShowView];
                                                 [SVProgressHUD dismiss];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendPatnerGoodWithAdd:(NSString*)add{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/personal/getCooperation"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (add.length) {
        [dic setObject:add forKey:@"address"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.collectionView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * dataArray =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 self.dataSouce = [NSMutableArray new];
                                                 for (NSDictionary * modelDic in dataArray) {
                                                     TMGPatnerModel * model = [TMGPatnerModel mj_objectWithKeyValues:modelDic];
                                                     [self.dataSouce addObject:model];
                                                 }
                                                 [self reloadData];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.collectionView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

